package com.sgb.kjwl.view.ui.activity.self.shop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityShopPriceDetailsBinding;
import com.sgb.kjwl.di.shopping.DaggerShopComponent;
import com.sgb.kjwl.di.shopping.ShopModule;
import com.sgb.kjwl.model.entity.shopping.ShopInfoPublishEntity;
import com.sgb.kjwl.model.entity.shopping.ShopPriceInfo;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.self.publish.GoodsSpecActivity;
import com.sgb.kjwl.view.ui.adapter.shopping.ShopInfoAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.shopping.ShopPriceDetailsModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.GoodsPublishSkuListEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ShopPriceDetailsAct extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private Thread thread;
    private ActivityShopPriceDetailsBinding binding;
    @Inject
    ShopPriceDetailsModel shopdetailsmodel;
    /**
     * 一级联动数据
     **/
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     **/
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    /**
     * 三级联动数据
     **/
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCitySelect();
                    isLoaded = true;
                    thread = null;
                    break;
            }
        }
    };
    private String note;
    private ShopInfoAdapter shopInfoAdapter;
    private List<ShopPriceInfo.GoodsListBean> newShopList = new ArrayList<>();
    private String no1;
    private String no2;
    private String no3;
    private String name3;
    private String name2;
    private String name1;
    private ShopPriceInfo shoppriceinfos;
    private ShopInfoPublishEntity shopInfoPublishEntity;
    private String event_shopping_type;

    public static void start(Context context, String note) {
        Intent intent = new Intent();
        intent.putExtra("note", note);
        intent.setClass(context, ShopPriceDetailsAct.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerShopComponent.builder()
                .appComponent(appComponent)
                .shopModule(new ShopModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_shop_price_details);
        binding.backView.setOnClickListener(this);
        binding.itvAddressSelect.setOnWholeItemClickListener(this);
        binding.ok.setOnClickListener(this);
    }

    @Override
    protected void init() {
        event_shopping_type = SharedPreferenceUtil.getInstance().getString("EVENT_SHOPPING_TYPE", "");
        note = getIntent().getStringExtra("note");
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        shopdetailsmodel.getQuoteGoodsInfo(note);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                if (!TextUtils.isEmpty(event_shopping_type)) {
                    shopdetailsmodel.showH5Url(note);
                } else {
                    shopdetailsmodel.startH5data(note);
                }
                break;
            case R.id.itv_address_select://省市区选择弹窗
                if (addressEntityList != null) {
                    showCitySelect();
                } else {
                    shopdetailsmodel.getAddressModel();
                }
                break;
            case R.id.ok://确认按钮
                if (newShopList != null && newShopList.size() > 0) {
                    initviewdata();
                    if (isFillMoney(newShopList)) {
                        String content = binding.itvAddressSelect.getContent();
                        if (!TextUtils.isEmpty(content)) {
                            String[] split = content.split("/");
                            if (split[0].equals("null")) {
                                MToast.showToast(this, "请选择货源所在地");
                                return;
                            }
                            if (split[1].equals("null")) {
                                MToast.showToast(this, "请选择货源所在地");
                                return;
                            }
                            if (split[2].equals("null")) {
                                MToast.showToast(this, "请选择货源所在地");
                                return;
                            }
                            QuotePublishData();
                        } else {
                            MToast.showToast(this, "请选择货源所在地");
                        }
                    } else {
                        MToast.showToast(this, "请填写至少一个商品价格");
                    }
                } else {
                    MToast.showToast(this, "请填写至少一个商品价格");
                }
                break;
            default:
                break;
        }
    }


    private boolean isFillMoney(List<ShopPriceInfo.GoodsListBean> goodsList) {
        for (int i = 0; i < goodsList.size(); i++) {
            if (!TextUtils.isEmpty(goodsList.get(i).getPrice())) {
                return true;
            }
        }
        return false;
    }


    private void showCitySelect() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
            }
            String content = addressEntityList.get(options1).getName()
                    + "/" + opt2.get(options1).get(options2).getName()
                    + "/" + areaName;
            name1 = addressEntityList.get(options1).getName();
            name2 = opt2.get(options1).get(options2).getName();
            name3 = areaName;
            no1 = addressEntityList.get(options1).getNo();
            no2 = opt2.get(options1).get(options2).getNo();
            no3 = opt3.get(options1).get(options2).get(options3).getNo();
            binding.itvAddressSelect.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCitySelect();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private void initJsonData() {
        //城市列表
        List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_address_select://省市区选择弹窗
                if (addressEntityList != null) {
                    showCitySelect();
                } else {
                    shopdetailsmodel.getAddressModel();
                }
                break;

        }
    }

    //拿到详情数据
    public void setQuoteGoodsInfo(ShopPriceInfo data) {
        if (data == null) {
            return;
        }
        this.shoppriceinfos = data;
        binding.companyName.setText(data.getCompanyName() + "");
        binding.priceExplain.setText(data.getDescribe());

        newShopList.clear();
        //hasQuote = true时为报过价的数据
        if (data.isHasQuote()) {
            binding.tvTitles.setText("修改报价");
            List<ShopPriceInfo.ItemListBean> listBeanList = data.getItemList();
            if (listBeanList != null) {
                //组装商品数据
                for (int i = 0; i < listBeanList.size(); i++) {
                    ShopPriceInfo.GoodsListBean item = new ShopPriceInfo.GoodsListBean();
                    item.setItemNo(listBeanList.get(i).getNo());
                    item.setTcatName(listBeanList.get(i).getTcatName());
                    item.setAttr(getAttrStr(listBeanList.get(i).getAttrList()));
                    item.setType("1");
                    item.setStrongLevel("");
                    item.setNum(listBeanList.get(i).getNum());
                    item.setGoodsBrand(listBeanList.get(i).getBrandName());
                    item.setUnit(listBeanList.get(i).getUnit());
                    item.setStatus(listBeanList.get(i).getStatus());
                    item.setNo(listBeanList.get(i).getEnquiryNo());
                    newShopList.add(item);
                }
            }

            List<ShopPriceInfo.ConcreteListBean> concreteList = data.getConcreteList();
            if (concreteList != null) {
                //组装商砼数据
                for (int i = 0; i < concreteList.size(); i++) {
                    ShopPriceInfo.GoodsListBean item = new ShopPriceInfo.GoodsListBean();
                    item.setItemNo(concreteList.get(i).getNo());
                    item.setTcatName(concreteList.get(i).getTcatName());
                    if (!TextUtils.isEmpty(getAdmixtureStr(concreteList.get(i).getAdmixtureFactList()))) {
                        item.setAttr(getAdmixtureStr(concreteList.get(i).getAdmixtureFactList()) + " " + "强度等级：" + concreteList.get(i).getStrongLevel());
                    } else {
                        item.setAttr("强度等级：" + concreteList.get(i).getStrongLevel());
                    }
                    item.setType("2");
                    item.setStrongLevel(concreteList.get(i).getStrongLevel());
                    item.setNum(concreteList.get(i).getNum());
                    item.setGoodsBrand(concreteList.get(i).getBrandName());
                    item.setUnit(concreteList.get(i).getUnit());
                    item.setStatus(concreteList.get(i).getStatus());
                    item.setNo(concreteList.get(i).getEnquiryNo());
                    newShopList.add(item);
                }
            }

            List<ShopPriceInfo.GoodsListBean> priceList = data.getGoodsList();
            for (int x = 0; x < priceList.size(); x++) {
                for (int y = 0; y < newShopList.size(); y++) {
                    //把价格赋值给相同No得那条数据
                    if (priceList.get(x).getItemNo().equals(newShopList.get(y).getItemNo())) {
                        newShopList.get(y).setPrice(priceList.get(x).getPrice());
                        newShopList.get(y).setGoodsSourceArea(priceList.get(x).getGoodsSourceArea());
                        newShopList.get(y).setGoodsSourceAreaNo(priceList.get(x).getGoodsSourceAreaNo());
                        newShopList.get(y).setBrand(priceList.get(x).getBrand());
                    }
                }
            }

            if (!TextUtils.isEmpty(getGoodsSourceArea(newShopList))) {
                String goodsSourceArea = data.getGoodsList().get(0).getGoodsSourceArea();
                String[] split = goodsSourceArea.split("/");
                name1 = split[0];
                name2 = split[1];
                name3 = split[2];
                binding.itvAddressSelect.setContent(getGoodsSourceArea(newShopList));
            }
            if (!TextUtils.isEmpty(getGoodsSourceAreaNo(newShopList))) {
                String goodsSourceArea = data.getGoodsList().get(0).getGoodsSourceAreaNo();
                String[] split = goodsSourceArea.split("/");
                no1 = split[0];
                no2 = split[1];
                no3 = split[2];
            }
        } else {
            newShopList = data.getGoodsList();
            binding.tvTitles.setText("报价");
            binding.itvAddressSelect.setContent("");
        }
        shopInfoAdapter = new ShopInfoAdapter(this, newShopList);
        binding.shoplistview.setAdapter(shopInfoAdapter);
    }

    private String getGoodsSourceArea(List<ShopPriceInfo.GoodsListBean> newShopList) {
        for (int x = 0; x < newShopList.size(); x++) {
            if (!TextUtils.isEmpty(newShopList.get(x).getGoodsSourceArea())) {
                return newShopList.get(x).getGoodsSourceArea();
            }
        }
        return "";
    }

    private String getGoodsSourceAreaNo(List<ShopPriceInfo.GoodsListBean> newShopList) {
        for (int x = 0; x < newShopList.size(); x++) {
            if (!TextUtils.isEmpty(newShopList.get(x).getGoodsSourceAreaNo())) {
                return newShopList.get(x).getGoodsSourceAreaNo();
            }
        }
        return "";
    }

    private String getAttrStr(List<ShopPriceInfo.AttristBean> attristBeans) {
        String attrString = "";
        if (attristBeans != null) {
            for (int a = 0; a < attristBeans.size(); a++) {
                if (!TextUtils.isEmpty(attristBeans.get(a).getParamValName())) {
                    attrString = attrString + attristBeans.get(a).getParamName() + ": " + attristBeans.get(a).getParamValName() + " ";
                } else {
                    attrString = attrString + attristBeans.get(a).getParamName() + " ";
                }
            }
        }
        return attrString;

    }

    private String getAdmixtureStr(List<ShopPriceInfo.AdmixtureFactListBean> admixtureFactListBeans) {
        String attrString = "";
        if (admixtureFactListBeans != null) {
            for (int a = 0; a < admixtureFactListBeans.size(); a++) {
                if (!TextUtils.isEmpty(admixtureFactListBeans.get(a).getSpec())) {
                    attrString = attrString + admixtureFactListBeans.get(a).getAdmixtureName() + ": " + admixtureFactListBeans.get(a).getSpec() + " ";
                } else {
                    attrString = attrString + admixtureFactListBeans.get(a).getAdmixtureName() + " ";
                }
            }
        }
        return attrString;
    }


    //    提交报价信息
    private void QuotePublishData() {

//        创建数据对象传参
        List<ShopInfoPublishEntity> shopinfolist = new ArrayList<>();
        for (int i = 0; i < newShopList.size(); i++) {
            //只把价格填了的传给后台
            if (!TextUtils.isEmpty(newShopList.get(i).getPrice())) {
                //创建对象添加到数据中
                shopInfoPublishEntity = new ShopInfoPublishEntity();
                if (TextUtils.isEmpty(newShopList.get(i).getBrand())) {
                    shopInfoPublishEntity.setBrand("");//品牌
                } else {
                    shopInfoPublishEntity.setBrand(newShopList.get(i).getBrand() + "");//品牌
                }
                shopInfoPublishEntity.setCityName(name2 + "");//发货市
                shopInfoPublishEntity.setCityNo(no2 + "");//发货市编码
                shopInfoPublishEntity.setContacts(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "") + "");//联系人
                if (TextUtils.isEmpty(binding.priceExplain.getText().toString().trim())) {
                    shopInfoPublishEntity.setDescription("");//补充说明
                } else {
                    shopInfoPublishEntity.setDescription(binding.priceExplain.getText().toString().trim() + "");//补充说明
                }
                shopInfoPublishEntity.setDistrictName(name3 + "");//发货区
                shopInfoPublishEntity.setDistrictNo(no3 + "");//发货区编码
                if (TextUtils.isEmpty(newShopList.get(i).getNo())) {
                    shopInfoPublishEntity.setEnquiryNo(note + "");//询价单业务编号
                } else {
                    shopInfoPublishEntity.setEnquiryNo(newShopList.get(i).getNo() + "");//询价单业务编号
                }
                shopInfoPublishEntity.setItemNo(newShopList.get(i).getItemNo() + "");//商品业务单编号
                shopInfoPublishEntity.setPrice(newShopList.get(i).getPrice() + "");//价格
                shopInfoPublishEntity.setProvinceName(name1 + "");//发货省
                shopInfoPublishEntity.setProvinceNo(no1 + "");//发货省编号
                //用户信息
                shopInfoPublishEntity.setPurchaser(shoppriceinfos.getSupplier() + "");//采购商业务编号getCompanyNo
                shopInfoPublishEntity.setPurchaserName(shoppriceinfos.getSupplierName() + "");//采购商业务名称getCompanyName
                shopInfoPublishEntity.setSupplier(shoppriceinfos.getCompanyNo() + "");//供应商业务编号getSupplier
                shopInfoPublishEntity.setSupplierName(shoppriceinfos.getCompanyName() + "");//供应商业务名称getSupplierName
                shopInfoPublishEntity.setTel(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "") + "");//联系方式
                shopInfoPublishEntity.setStatus(newShopList.get(i).getStatus() + "");//报价状态
                shopInfoPublishEntity.setType(newShopList.get(i).getType() + "");//商品类型
                shopinfolist.add(shopInfoPublishEntity);
            }
        }
        shopdetailsmodel.setQuotePublish(shopinfolist);
    }

    private void initviewdata() {
        int childCount = binding.shoplistview.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = binding.shoplistview.getChildAt(i);
            EditText editText = childAt.findViewById(R.id.ed_shop_brand);
            EditText edshopmoney = childAt.findViewById(R.id.ed_shop_money);
            newShopList.get(i).setBrand(editText.getText().toString().trim() + "");
            newShopList.get(i).setPrice(edshopmoney.getText().toString().trim() + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void setView() {
        if (!TextUtils.isEmpty(event_shopping_type)) {
            shopdetailsmodel.showH5Url(note);
        } else {
            shopdetailsmodel.startH5data(note);
        }
        finish();
    }
}
